#!/bin/sh
# Copyright (C) 2024 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

set -e

usage() {
  echo "Usage: $(basename $0) COMMAND [ARGS]"
  echo
  echo "Initialize build environment:"
  echo "  $(basename $0) init [--manifest <manifest xml>] [--manifest-dir <dir path>]"
  echo "                           [--reference <mirror path>] [--internal]"
  echo "    --manifest <manifest xml>: name of the manifest to be used for initialization"
  echo "    --manifest-dir <dir path>: path to a directory containing repo manifest file(s)"
  echo "    --reference <mirror path>: path to local mirror, initialized previously with 'repo init --mirror'"
  echo "    --internal: fetch internal repositories, available only inside The Qt Company network."
}

while test -n "$1"; do
  case "$1" in
    "help" | "--help" | "-h")
      usage
      exit 0
      ;;
    "--reference" | "-r")
      shift
      REFERENCE=$1
      ;;
    "--device" | "-d")
      shift
      # ignored
      ;;
    "--repo-url")
      shift
      REPO_URL="--repo-url $1"
      ;;
    "--manifest")
      shift
      MANIFEST=$1
      ;;
    "--manifest-dir")
      shift
      MANIFEST_DIR="$(readlink -f $1)"
      ;;
    "--internal")
      PROJECT_GROUPS="all"
      ;;
    *)
      if [ -n "$COMMAND" ]; then
        echo "Unknown argument: $1"
        usage
        exit 1
      fi
      COMMAND=$1
      ;;
  esac
  shift
done

if [ -z "${COMMAND}" ]; then
  usage
  exit 1
fi

DIR=$(dirname $(readlink -f $0))
if [ -n "${REFERENCE}" ]; then
  REFERENCE="--reference $(readlink -f ${REFERENCE})"
fi

if [ -z "${REPO_URL}" ]; then
  REPO_URL="--repo-url https://github.com/theqtcompany/git-repo"
fi

PROJECT_GROUPS=${PROJECT_GROUPS:-default}
MANIFEST=${MANIFEST:-manifest.xml}
MANIFEST_DIR=${MANIFEST_DIR:-${DIR}/scripts}

get_repo() {
  REPO="./repo"
  if [ -n "$(command -v repo)" ]; then
    REPO="repo"
  elif [ ! -x "./repo" ]; then
    curl -s https://storage.googleapis.com/git-repo-downloads/repo > "./repo"
    chmod +x ./repo
  fi
}

init() {
  mkdir -p .repo/manifests
  cp ${MANIFEST_DIR}/${MANIFEST} .repo/manifests/default.xml
  ${REPO} init ${REPO_URL} -u ${PWD}/.repo/repo -b default -g "${PROJECT_GROUPS}" ${REFERENCE}
  ${REPO} sync --optimized-fetch

  if [ ! -e "sources/meta-boot2qt" ]; then
    ln -s ${DIR} sources/meta-boot2qt
  fi

  if [ ! -e "setup-environment.sh" ]; then
    ln -s ${DIR}/scripts/setup-environment.sh setup-environment.sh
  fi

  ln -sfn meta-boot2qt/meta-boot2qt-distro/conf/templates/default sources/templates

  # handle lfs repos which need manual lfs pull
  LFS_REPOS=$(grep filter=lfs -l sources/*/.gitattributes 2>/dev/null || true)
  for repo in ${LFS_REPOS}; do
    ( cd $(dirname ${repo}); git lfs pull )
  done
}

get_repo

case "$COMMAND" in
  "init")
    init
    ;;
  "mirror")
    mirror
    ;;
  *)
    echo "Unknown command"
    usage
    exit 1
    ;;
esac
